package cn.dgut.jy.soro.service.impl;

import cn.dgut.jy.soro.entity.Cart;
import cn.dgut.jy.soro.entity.User;
import cn.dgut.jy.soro.repository.CartRepository;
import cn.dgut.jy.soro.repository.UserRepository;
import cn.dgut.jy.soro.service.UserService;
import cn.dgut.jy.soro.util.SHA256Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {
    private UserRepository userRepository;

    private CartRepository cartRepository;

    @Autowired
    public UserServiceImpl(UserRepository userRepository, CartRepository cartRepository) {
        this.userRepository = userRepository;
        this.cartRepository = cartRepository;
    }

    @Override
    public User login(String mobile, String password) {
        return userRepository.findByMobileAndPassword(mobile, password);
    }

    @Override
    public Boolean join(String username, String mobile, String email, String password, Integer authority) {
        if(userRepository.findByUsernameOrMobileOrEmail(username, mobile, email) != null ||
                username.length() < 6 || username.length() > 20 ||
                mobile.length() != 11 ||
                password.length() < 8 ||
                password.length() > 16 ||
                email.length() < 4 ||
                email.length() > 32) {
            return false;
        }
        User user = new User();
        Cart cart = new Cart();
        cart = cartRepository.saveAndFlush(cart);
        user.setUsername(username);
        user.setMobile(mobile);
        user.setEmail(email);
        user.setAuthority(authority);
        user.setPassword(SHA256Util.getSHA256Str(password));
        user.setCart_id(cart.getId());
        user = userRepository.saveAndFlush(user);
        cart.setUserId(user.getId());
        cartRepository.save(cart);
        return true;
    }

    @Override
    public User getPersonalInfo(Integer userId) {
        if(!userRepository.findById(userId).isPresent()) {
            return null;
        }

        return userRepository.findById(userId).get();
    }

    @Override
    public Boolean changePassword(String mobile, String email, String newPassword) {
        User user = userRepository.findByMobileAndEmail(mobile, email);
        if(user == null) {
            return false;
        }

        user.setPassword(SHA256Util.getSHA256Str(newPassword));

        return true;
    }
}
